#include "interface.h"

Animal* AnimalCreator::doMakeAnimal(int key, ifstream &ifst) {
	Animal *animal;
	switch (key) {
	case 1:
		animal = new Fish;
		break;
	case 2:
		animal = new Bird;
		break;
	default:
		return 0;
	}
	animal->setData(ifst);
	return animal;
}

void Bird::setData(ifstream &ifst) {
	ifst >> migration;
	ifst >> name;
}

void Bird::print(ofstream &ofst) {
	ofst << "Это птица по имени " << name << " и она "
			<< (migration ? "перелётная" : "терпет холода") << endl;
}

void Fish::setData(ifstream &ifst) {
	int life1;
	ifst >> life1;
	ifst >> name;
	switch (life1) {
	case 1:
		life = Fish::SEA;
		break;
	case 2:
		life = Fish::LIKE;
		break;
	case 3:
		life = Fish::RIVER;
		break;
	default:
		life = Fish::UNKNOW;
		break;
	}
}

void Fish::print(ofstream &ofst) {
	ofst << "Это рыбка по имени " << name;
	switch (life) {
	case Fish::SEA:
		ofst << " которая живёт в море" << endl;
		break;
	case Fish::LIKE:
		ofst << " которая живёт в озере" << endl;
		break;
	case Fish::RIVER:
		ofst << " которая живёт в реке" << endl;
		break;
	default:
		ofst << " которая живёт неизвестно где... :'(" << endl;
		break;
	}
}

void Container::readFromFile(ifstream &ifst, Creator &animalCreator) {
	while (!ifst.eof()) {
		//Определяем тип животного
		int key;
		ifst >> key;
		//Передаём ключ креатору
		Animal *animal = animalCreator.doMakeAnimal(key, ifst);
		if (animal != 0) {
			Element *newNode = new Element;
			newNode->value = animal;
			if (size == 0) {
				newNode->next = NULL;
				newNode->previous = NULL;
				begin = newNode;
				end = newNode;
				++size;
			} else {
				Element *current = end;
				current->next = newNode;
				newNode->previous = current;
				newNode->next = NULL;
				end = newNode;
				++size;
			}
		}
	}
}

void Container::print(ofstream & ofst) {
	Element *current = begin;
	ofst << "Контейнер содержит в себе " << size << " элементов" << endl;
	while (current != NULL) {
		current->value->print(ofst);
		current = current->next;
	}
}

Container::~Container() {
	size = 0;
	Element *current = begin;
	while (current->next != NULL) {
		current = current->next;
		delete current->previous->value;
		delete current->previous;
	}
	delete end->value;
	delete end;
}
